<?php
namespace App\Models;

class MemberWithdraw extends BaseModel
{
    protected $table = 'member_withdraw';
    protected $member;
    protected $shop;
    protected $memberCommission;

    protected $statusDesc = [
        1 => '待审核',
        2 => '已审核',
        3 => '已完成',
        4 => '已驳回'
    ];

    protected $statusColor = [
        1 => 'black',
        2 => 'blue',
        3 => 'green',
        4 => 'red'
    ];

    protected $accountType = [
        1 => '微信',
        2 => '支付宝'
    ];

    protected $rules = [
        'mid' => 'required|integer',
        'shop_id' => 'required|integer',
        'account_type' => 'required|in:1,2',
        'account' => 'required',
        'money' => 'required|integer'
    ];
    protected $message = [
        'mid.required' => '请填写用户ID',
        'mid.integer' => '用户ID格式不正确',
        'shop_id.required' => '请填写店铺ID',
        'shop_id.integer' => '店铺ID格式不正确',
        'account_type.required' => '请选择账号类型',
        'account_type.in' => '账号类型不存在',
        'account.required' => '请填写提现账号',
        'money.required' => '请填写提现金额',
        'money.integer' => '提现金额应为整数'
    ];

    public function __construct()
    {
        parent::__construct();
        $this->member = new Member();
        $this->shop = new Shop();
        $this->memberCommission = new MemberCommission();
    }

    public function getWithdrawList($where)
    {
        $rows = $this->leftJoin('member', 'member_withdraw.mid','=','member.id')
            ->multiWhere($where)
            ->select('member_withdraw.*','member.nickname')
            ->orderBy("member_withdraw.id",'desc')->paginate();

        $rows->map(function($item) {
            $item['status_text'] = $this->statusDesc[$item['status']];
            $item['status_color'] = $this->statusColor[$item['status']];
            $item['type_text'] = $this->accountType[$item['account_type']];
            return $item;
        });

        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 5);
        }

        return $rows;
    }

    public function addData()
    {
        $data['mid'] = request('mid');
        $data['shop_id'] = request('sid');
        $memberInfo = $this->member->_getOneById($data['mid']);
        if(!$memberInfo) {
            $this->error = '该用户不存在';
            return false;
        }
        $shopInfo = $this->shop->_getOneById($data['shop_id']);
        if(!$shopInfo) {
            $this->error = '店铺不存在';
            return false;
        }
        $data['account_type'] = request('account_type');
        $data['account'] = request('account');
        $data['admin_id'] = $memberInfo['admin_id'];
        $data['money'] = request('money');
        if(request('reason')) {
            $data['reason'] = request('reason');
        }
        if(!$this->checkWithdrawToday($data['mid'])) {
            $this->error = '今天已提交过提现申请';
            return false;
        }
        if($data['account_type'] == 2) {
            $data['account_name'] = request('account_name');
            if(!$data['account_name']) {
                $this->error = '请输入收款人姓名';
                return false;
            }
        }
        if (!$this->_validate($data)) {
            return false;
        }
        if($data['money'] < $shopInfo['withdraw_min']) {
            $this->error = '最小提现金额为￥'.$shopInfo['withdraw_min'].'元';
            return false;
        }
        $commission = new MemberCommission();
        $where['mid'] = $data['mid'];
        $money = $data['money'];
        $commissionInfo = $commission->_getOne($where);
        if(!$commissionInfo || $commissionInfo['able_money'] < $money) {
            $this->error = '您的可提现佣金小于'.$money.'元';
            return false;
        }

        $this->_start();
        try{
            // 保存申请数据
            $this->_save($data);
            $commission->_inc($where,'freeze_money', $money); //冻结金额增加
            $commission->_dec($where,'able_money', $money); // 提现金额减少

            $this->_commit();
            return true;
        }catch(\Exception $e) {
            $this->_rollBack();
            $this->error = $e->getMessage() ? $e->getMessage() : '提现申请提交失败';
            return false;
        }

    }

    // 检测当天是否已提交过申请
    public function checkWithdrawToday($mid)
    {
        $where['mid'] = $mid;
        $now = strtotime(date('Y-m-d 00:00:00'));
        $info = $this->where('created_at','>=',date('Y-m-d 00:00:00'))
            ->where('created_at','<',date('Y-m-d 00:00:00', $now + 86400))
            ->get();
        if(count($info)){
            return false;
        }
        return true;
    }

    // 审核提现申请
    public function withDrawAudit($id, $data, $mid, $money)
    {
        $this->_start();
        try{
            $where['mid'] = $mid;
            // 更新提现申请信息
            $this->_update(['id' => $id], $data);

            // 修改佣金账户数据
            if(in_array($data['status'],[3,4])) {
                $commission = new MemberCommission();
                $commission->_dec($where,'freeze_money', $money);
                if($data['status'] == 3) {
                    // 完成时，已提现金额增加
                    $commission->_inc($where,'already_money', $money);
                }
                if($data['status'] == 4) {
                    // 驳回时，可提现金额增加
                    $commission->_inc($where,'able_money', $money);
                }
            }
            $this->_commit();
            return true;
        }catch(\Exception $e) {
            $this->_rollBack();
            return false;
        }
    }

}